﻿/**************************************************************
 *
 * 唯一标识：c8efb793-8f6f-48bb-a575-4710a3afc676
 * 命名空间：Sgr.UPMS.Application.Commands.Roles
 * 创建时间：2023/8/27 17:35:17
 * 机器名称：DESKTOP-S0D075D
 * 创建者：antho
 * 电子邮箱：fengqinhua2016@163.com
 * 描述：创建角色命令处理器
 *
 **************************************************************/

using MediatR;
using Sgr.Application.Commands;
using Sgr.Application.Queries;
using Sgr.Exceptions;
using Sgr.UPMS.Domain.Roles;
using System.Threading;
using System.Threading.Tasks;

namespace Sgr.UPMS.Application.Commands.Roles
{
    /// <summary>
    /// 创建角色命令处理器
    /// </summary>
    public class CreateRoleCommandHandle : IRequestHandler<CreateRoleCommand, CommandResult<bool>>
    {
        private readonly IRoleRepository _roleRepository;
        private readonly IRoleManage _roleManage;
        private readonly ICurrentUser _currentUser;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="roleRepository">角色仓储</param>
        /// <param name="roleManage">角色管理器</param>
        /// <param name="currentUser">当前用户</param>
        public CreateRoleCommandHandle(
            IRoleRepository roleRepository,
            IRoleManage roleManage,
            ICurrentUser currentUser)
        {
            _roleRepository = roleRepository;
            _roleManage = roleManage;
            _currentUser = currentUser;
        }

        /// <summary>
        /// 处理创建角色命令
        /// </summary>
        /// <param name="request">命令请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>处理结果</returns>
        public async Task<CommandResult<bool>> Handle(CreateRoleCommand request, CancellationToken cancellationToken)
        {
            long orgId = QueryHelper.GetOrgId(_currentUser);

            // 创建角色
            Role role = await _roleManage.CreateNewAsync(
                request.RoleName,
                orgId,
                request.OrderNumber,
                request.Remarks,
                cancellationToken);

            // 保存角色到仓储
            await _roleRepository.InsertAsync(role, cancellationToken);

            // 返回成功结果
            return CommandResult.Success(true, "角色创建成功");
        }
    }
}